package chapter14;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-03-26 下午12:05
 */
public class TransactionTest {
    public static void main(String[] args) {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://192.168.100.66/java_test?useSSL=false&serverTimezone=UTC&amp";
        String userName = "root";
        String password = "crscd123@";

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }

        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, userName, password);
            Statement stmt = conn.createStatement();
            conn.setAutoCommit(false);
            String sql_insert = "INSERT INTO book (name, price) VALUES ('test1',123.3);";
            String sql_insert1 = "INSERT INTO book (name, price) VALUES ('test1',123.3);";
            String sql_insert2 = "INSERT INTO book (name, price) VALUES ('test1','121zf');";
            stmt.addBatch(sql_insert);
            stmt.addBatch(sql_insert1);
            stmt.addBatch(sql_insert2);
            stmt.addBatch(sql_insert);
            stmt.addBatch(sql_insert);
            int[] result = stmt.executeBatch();
            System.out.println("result:" + Arrays.toString(result));
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            if (null != conn) {
                try {
                    conn.rollback();
                    System.out.println("rollback");
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
